<?php

namespace app\common\model;

use think\Model;

class User extends Model
{
    protected $pk = 'uid';
    protected $type = [
        'money'     =>  'float',
        'sd_money'  =>  'float',
    ];
    public function getLevalAttr($value)
    {
        $leval_text = get_db_config(true)['user_leval_cfg']['name'];
        return $leval_text[$value];
    }
    public function getStatusTextAttr($value,$data)
    {
        $status = [-1=>'删除',0=>'<span style="color:red;">禁用</span>',1=>'正常',2=>'待审核'];
        return $status[$data['status']];
    }
    public function getPidNicknameAttr($value,$data)
    {
        return get_nickname($data['pid']);
    }
    
    /**
     * 查询所有指定代数下线人数
     * @return array uid
     */
    public function GetSon($uid,$lv){
        $ids = array();
        for ($i=0;$i<$lv;$i++){
            $ids = array_merge($ids,(array)self::GetDesignSon($uid,$i+1));
        }
        return $ids;
    }
    
    /**
     * 查询指定代数下线   注意是某代人数
     * @param $uid 当前的用户ID
     * @param $lv 	查询的层数
     * @return array uid or null
     */
    public function GetDesignSon($uid,$lv=1,$i=0){
        $i++;
        if ( $i < $lv ){
            $ids = $this->findsonid($uid);
            return self::GetDesignSon($ids,$lv,$i);
        }else {
            return $this->findsonid($uid);
        }
    }
    
    public function findsonid($idarr){
        if (!is_array($idarr))
            $idarr = array($idarr);
        $ids = $this->where('pid','in',$idarr)->column('uid');
        if (!$ids){
            return ;
        }
        return $ids;
    }
    
    /**
     * 递归查找上级的淘宝、京东pid
     */
    public function get_prev_pid($field,$pid,$i=0)
    {
        $i++;
        $pinfo = $this->get($pid);
        $bool = true;
        if ($pinfo){
            //如果上级是买手上以级别
            if ($i==1){
                if ($pinfo->getData('leval')>0){
                    $tb_pid = $pinfo->$field;
                    if ($tb_pid){
                        return $tb_pid;
                        $bool = false;
                    }
                }
            }else {
                //找达人,或者公司
                if ($pinfo->getData('leval')>1){
                    $tb_pid = $pinfo->$field;
                    if ($tb_pid){
                        return $tb_pid;
                        $bool = false;
                    }
                }
            }
            if ($bool){
                return self::get_prev_pid($field,$pinfo['pid'],$i);
            }
        }
    }
    
    /**
     * 查询所有下线
     */
    public function get_all_son($uids,$re=[])
    {
        //if (!is_array($uids)) $uids = [$uids];
        $sons_uid = $this->where('pid','in',$uids)->column('uid');
        if ($sons_uid){
            $re = array_merge($sons_uid,$re);
            return self::get_all_son($sons_uid,$re);
        }else {
            return $re;
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
